<template>
  <div id="shuziren">
    <div class="step-two">
      <div class="two-search-box">
        <div class="two-search">
          <div>学生信息：</div>
          <el-input
            v-model="form.nickName"
            clearable
            style="width: 360px"
            placeholder="输入姓名、学号、班级信息"
          />
          <div
            class="all-btn"
            @click="search"
          >搜索</div>
        </div>
        <div class="two-btns">
          <div
            class="all-btn"
            @click="handleAddStudent()"
          >
            <el-icon>
              <CirclePlus />
            </el-icon>
            添加学生
          </div>
          <div
            class="all-btn"
            @click="delStudents()"
          >
            <el-icon>
              <Delete />
            </el-icon>
            批量删除
          </div>
          <div
            class="all-btn"
            @click="handleClickUpload()"
          >
            <el-icon>
              <Upload />
            </el-icon>
            批量导入
          </div>
          <div
            class="all-btn"
            @click="download2()"
          >
            <el-icon>
              <Download />
            </el-icon>
            学生数据下载
          </div>
        </div>
      </div>
      <div class="all-box">
        <div>
          <el-table
            :data="tableData"
            @selection-change="handleSelectionChange"
            style="width: 100%"
          >
            <el-table-column
              type="selection"
              width="55"
            />
            <!-- 加序号 -->
            <el-table-column
              type="index"
              label="序号"
              width="60"
            ></el-table-column>
            <el-table-column
              prop="nickName"
              label="姓名"
            />
            <el-table-column
              prop="xnum"
              label="学号"
            />
            <el-table-column label="性别">
              <template #default="scope">
                {{scope.row.sex == 1 ? "女" : "男" }}
              </template>
            </el-table-column>
            <el-table-column
              prop="phonenumber"
              label="联系方式"
            />
            <el-table-column
              prop="email"
              label="邮箱"
            />
            <el-table-column
              label="操作"
              width="200"
            >
              <template #default="scope">
                <div class="table-btns">
                  <div @click="handleEditStudent(scope.row)">修改</div>
                  <div @click="initPassword(scope.row)">初始密码</div>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <div class="all-page">
            <el-pagination
              v-model:current-page="form.page"
              :page-size="10"
              layout="prev, pager, next, jumper"
              :total="total"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </div>

    <el-dialog
      v-model="dialogUpload"
      :close-on-click-modal="false"
      width="650"
      align-center
      :before-close="handleCloseUpload"
    >
      <div class="my-dialog">
        <div class="my-dialog-content">
          <div class="dialog-title">批量导入</div>
          <div
            class="dialog-btn"
            @click="download1"
          >
            <el-icon>
              <Download />
            </el-icon>
            下载模版
          </div>
          <el-upload
            ref="upload"
            class="avatar-uploader"
            :key="uploadKey"
            action="/dev/system/user/importStudent"
            :on-success="handleSuccess"
            :before-upload="beforeUpload"
            :on-error="handleError"
            :limit="1"
            accept=".xls,.xlsx"
            :auto-upload="false"
          >
            <div class="dialog-btn">
              <el-icon>
                <Upload />
              </el-icon>
              点击上传
            </div>
          </el-upload>
          <div class="dialog-txt">先下载模版，填写信息后上传，只能上传xls格式文件，且不超过50MB</div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            color="#155EEF"
            @click="submitUpload()"
          >
            确定
          </el-button>
          <el-button @click="dialogUpload = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="dialogAdd"
      :close-on-click-modal="false"
      width="830"
      align-center
      :before-close="handleCloseAdd"
    >
      <div class="my-dialog">
        <div class="my-dialog-content dialog-add">
          <div
            class="dialog-title"
            v-if="isEdit"
          >修改学生</div>
          <div
            class="dialog-title"
            v-else
          >添加学生</div>
          <div class="dialog-form">
            <div>
              <div class="label">学号：</div>
              <el-input
                v-model="addForm.userName"
                placeholder="请输入"
              ></el-input>
            </div>
            <div>
              <div class="label">昵称：</div>
              <el-input
                v-model="addForm.nickName"
                placeholder="请输入"
              ></el-input>
            </div>
            <div v-if="!isEdit">
              <div class="label">密码：</div>
              <el-input
                v-model="addForm.password"
                placeholder="请输入"
              ></el-input>
            </div>
            <div>
              <div class="label">性别：</div>
              <el-radio-group v-model="addForm.sex">
                <el-radio
                  value="0"
                  size="large"
                >男</el-radio>
                <el-radio
                  value="1"
                  size="large"
                >女</el-radio>
              </el-radio-group>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="isEdit"
            color="#155EEF"
            @click="submitEdit()"
          >
            修改
          </el-button>
          <el-button
            v-else
            color="#155EEF"
            @click="submitAdd()"
          >
            确定
          </el-button>
          <el-button @click="dialogAdd = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      isEdit: false,
      dialogUpload: false,
      dialogAdd: false,
      uploadKey: 0, // 动态 key
      selectIdList: [],
      tableData: [],
      total: 0,
      form: {
        nickName: "",
        page: 1,
        limit: 10,
      },
      addForm: {
        userName: "学生05",
        nickName: "05昵称",
        password: "000000",
        sex: "0",
        status: "0",
        userId: "",
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    download1() {
      const url = `/system/user/studentTemplate`; // 接口路径（通过 Vite 代理转发）
      this.$axios
        .post(
          url,
          {},
          {
            responseType: "blob",
          }
        ) // 确保 responseType 设置为 blob

        .then((response) => {
          const blob = new Blob([response.data], {
            type: " application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
          });
          const link = document.createElement("a");
          link.href = window.URL.createObjectURL(blob);
          link.download = "导入模版.xlsx"; // 设置下载文件名
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        });
    },
    download2() {
      const url = `/system/user/studentExport`; // 接口路径（通过 Vite 代理转发）
      this.$axios
        .post(
          url,
          {},
          {
            responseType: "blob",
          }
        ) // 确保 responseType 设置为 blob

        .then((response) => {
          const blob = new Blob([response.data], {
            type: " application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
          });
          const link = document.createElement("a");
          link.href = window.URL.createObjectURL(blob);
          link.download = "学生数据.xlsx"; // 设置下载文件名
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        });
    },
    handleClickUpload() {
      this.dialogUpload = true;
    },
    handleAddStudent() {
      this.clearAddForm();
      this.isEdit = false;
      this.dialogAdd = true;
    },
    handleEditStudent(row) {
      console.log(row);
      this.clearAddForm();
      this.isEdit = true;
      this.addForm.userName = row.userName;
      this.addForm.nickName = row.nickName;
      this.addForm.sex = row.sex;
      this.addForm.status = row.status;
      this.addForm.userId = row.userId;
      this.dialogAdd = true;
    },
    clearAddForm() {
      this.addForm.userName = "";
      this.addForm.nickName = "";
      this.addForm.password = "";
      this.addForm.sex = "0";
      this.addForm.status = "0";
      this.addForm.userId = "";
    },
    // 手动触发上传
    submitUpload() {
      this.$refs.upload.submit(); // 调用 el-upload 的 submit 方法
    },
    submitAdd() {
      if (this.addForm.userName === "" || this.addForm.nickName === "") {
        this.$message.error("学号和昵称不能为空");
        return;
      }
      const url = `/system/user/addStudent`;
      const data = this.addForm;
      const loading = this.$loading({
        lock: true,
        text: "正在添加，请稍后...",
        background: "rgba(0, 0, 0, 0.7)",
      });
      this.$axios
        .post(url, data)
        .then((response) => {
          const res = response;
          this.$message.success(res.msg || "添加成功");
          this.dialogAdd = false;
          this.getList();
        })
        .finally(() => {
          loading.close();
        });
    },
    submitEdit() {
      if (this.addForm.userName === "" || this.addForm.nickName === "") {
        this.$message.error("学号和昵称不能为空");
        return;
      }
      const url = `/system/user/editUser`;
      const data = this.addForm;
      const loading = this.$loading({
        lock: true,
        text: "正在修改，请稍后...",
        background: "rgba(0, 0, 0, 0.7)",
      });
      this.$axios
        .post(url, data)
        .then((response) => {
          const res = response;
          this.$message.success(res.msg || "修改成功");
          this.dialogAdd = false;
          this.getList();
        })
        .finally(() => {
          loading.close();
        });
    },
    //初始化密码
    initPassword(row) {
      const url = `/system/user/resetPwdd?userId=${row.userId}`;
      const loading = this.$loading({
        lock: true,
        text: "正在初始化密码，请稍后...",
        background: "rgba(0, 0, 0, 0.7)",
      });
      this.$axios
        .post(url)
        .then((response) => {
          const res = response;
          this.$message.success(res.msg || "初始化密码成功");
        })
        .finally(() => {
          loading.close();
        });
    },
    handleSuccess(res, file) {
      console.log("上传成功：", res);
      this.$message.success("上传成功!");
      this.uploadKey += 1; // 修改 key 值，强制重新渲染组件
      this.dialogUpload = false;
      this.getList();
    },
    // 上传前的校验
    beforeUpload(file) {
      const isExcel =
        file.type === "application/vnd.ms-excel" || // .xls
        file.type ===
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; // .xlsx
      const isLt2M = file.size / 1024 / 1024 < 50; // 文件大小限制为 50MB

      if (!isExcel) {
        this.$message.error("只能上传 Excel 文件！");
      }
      if (!isLt2M) {
        this.$message.error("文件大小不能超过 50MB！");
      }

      return isExcel && isLt2M;
    },
    handleError() {
      this.$message.error("上传失败，请稍后再试!");
      this.uploadKey += 1; // 修改 key 值，强制重新渲染组件
    },
    handleSelectionChange(val) {
      console.log(val);
      this.selectIdList = val.map((item) => item.userId);
      console.log(this.selectIdList);
    },
    search() {
      this.form.page = 1;
      this.getList();
    },
    handleCloseAdd() {
      this.dialogAdd = false;
    },
    handleCurrentChange(currentPage) {
      this.form.page = currentPage;
      this.getList();
      console.log(currentPage, 333);
    },
    getList() {
      const url = `/system/role/student/list`;
      const params = this.form;
      this.loading = true;
      this.$axios
        .get(url, { params })
        .then((response) => {
          const res = response;
          this.tableData = res.data;
          this.total = res.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    delStudents() {
      if (this.selectIdList.length === 0) {
        this.$message.error("请选择学生");
        return;
      }
      const delstr = this.selectIdList.join(",");
      const url = `/system/user/batchDeleteStudent/${delstr}`;
      this.$confirm("是否删除？").then(() => {
        const loading = this.$loading({
          lock: true,
          text: "删除中，请稍后...",
          background: "rgba(0, 0, 0, 0.7)",
        });
        this.$axios
          .delete(url)
          .then((response) => {
            const res = response;
            this.$message.success(res.msg || "删除成功");
            this.getList();
          })
          .finally(() => {
            loading.close();
          });
      });
    },
  },
};
</script>
<style lang="scss" scoped>
#shuziren {
  .step-two {
    .all-box {
      padding: 38px 52px;
    }
    .all-btn {
      height: 36px;
      line-height: 36px;
      a {
        display: block;
        width: 100%;
        height: 100%;
        color: #0a5ff6;
        text-decoration: none;
      }
      &:hover {
        a {
          color: #fff;
        }
      }
    }
    .two-search-box {
      display: flex;
      justify-content: space-between;
    }
    .two-search {
      display: flex;
      align-items: center;
      gap: 10px;
      margin-bottom: 10px;
      :deep(.el-input__inner) {
        height: 38px;
      }
    }
    .two-btns {
      display: flex;
      gap: 10px;
    }
    .el-table {
      margin-bottom: 20px;
      :deep(th) {
        color: #7a8cb0;
      }
      .table-btns {
        display: flex;
        gap: 20px;
        > div {
          cursor: pointer;
          color: #457aff;
          &:hover {
            color: #2657b8;
          }
        }
      }
    }
  }
  .my-dialog {
    display: flex;
    justify-content: center;
    padding: 40px;
    .my-dialog-content {
      display: flex;
      flex-direction: column;
      justify-content: center;
      gap: 20px;
      &.dialog-add {
        width: 100%;
      }
      .dialog-title {
        font-size: 20px;
        color: #204077;
      }
      .dialog-btn {
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 6px;
        width: 460px;
        height: 50px;
        line-height: 50px;
        text-align: center;
        background: #eff5ff;
        border-radius: 6px;
        border: 1px solid #c1d6fe;
        font-size: 14px;
        color: #0a5ff6;
        cursor: pointer;
        &:hover {
          background: #c1d6fe;
          color: #0a5ff6;
        }
        a {
          display: block;
          width: 100%;
          height: 100%;
          color: #0a5ff6;
          text-decoration: none;
        }
      }
      .dialog-txt {
        font-size: 14px;
        color: #7b88a9;
      }
      .dialog-form {
        width: 80%;
        margin: 0 auto;
        display: flex;
        flex-direction: column;
        gap: 20px;
        > div {
          display: flex;
          justify-content: flex-start;
          align-items: center;
          .label {
            width: 64px;
          }
        }
      }
    }
  }
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
    > button {
      margin-left: 10px;
    }
  }
  :deep(.el-upload-list) {
    .el-upload-list__item-info {
      width: 100%;
      margin-left: 0;
      .el-upload-list__item-name {
        height: 70px;
        padding: 0 26px;
        box-sizing: border-box;
        background: #ffffff;
        border-radius: 10px;
        border: 1px solid #e4e3e4;
      }
    }
    .el-icon--close,
    .el-upload-list__item-status-label {
      right: 25px;
    }
  }
}
</style>